<script setup lang="ts">
import DataTable from './components/DataTable.vue';
import DataTableToolbar from './components/DataTableToolbar.vue';
import UserForm from './components/UserForm.vue';
import ConfirmDialog from '@/components/confirm-dialog/index.vue';
import { fetchUserPage, deleteUser, resetPassword } from '@/api/endpoints/system/user';
import type { User } from '@/api/endpoints/system/user';
import { toast } from '@/lib/toast';

const tableData = ref<User[]>([]);
const showUserForm = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const currentUser = ref<User | null>(null);
const showDeleteDialog = ref(false);
const deletingUser = ref<User | null>(null);
const loading = ref(false);

onMounted(async () => {
  await loadUserList();
});

async function loadUserList() {
  const res = await fetchUserPage();
  tableData.value = (res as any).data as User[];
}

function handleSearch(value: string) {
  console.log(value);
}

function handleAdd() {
  formMode.value = 'create';
  currentUser.value = null;
  showUserForm.value = true;
}

function handleEdit(user: User) {
  formMode.value = 'edit';
  currentUser.value = user;
  showUserForm.value = true;
}

function handleDelete(user: User) {
  deletingUser.value = user;
  showDeleteDialog.value = true;
}

async function confirmDeleteUser() {
  if (!deletingUser.value) {
    return;
  }

  loading.value = true;
  try {
    await deleteUser(deletingUser.value.id);
    toast.success('用户删除成功');
    await loadUserList();
    showDeleteDialog.value = false;
    deletingUser.value = null;
  } catch (error) {
    toast.error('用户删除失败');
    console.error('删除用户失败:', error);
  } finally {
    loading.value = false;
  }
}

function cancelDelete() {
  showDeleteDialog.value = false;
  deletingUser.value = null;
}

function handleFormSuccess() {
  loadUserList();
}

function handleFormClose() {
  showUserForm.value = false;
  currentUser.value = null;
}

function handleResetPassword(user: User) {
  resetPassword(user.id)
    .then(() => {
      toast.success('密码重置成功');
    })
    .catch(() => {
      toast.error('密码重置失败');
    });
}
</script>

<template>
  <div>
    <div class="hidden h-full flex-1 flex-col space-y-4 p-8 md:flex">
      <DataTableToolbar @search="handleSearch" @add="handleAdd" />
      <DataTable
        :table-data="tableData"
        @edit="handleEdit"
        @delete="handleDelete"
        @reset-password="handleResetPassword"
      />
    </div>

    <!-- 统一的用户表单 -->
    <UserForm
      :open="showUserForm"
      :mode="formMode"
      :user="currentUser"
      @close="handleFormClose"
      @success="handleFormSuccess"
    />

    <!-- 删除确认对话框 -->
    <ConfirmDialog
      v-model:open="showDeleteDialog"
      :title="`确认删除用户${deletingUser?.name}`"
      :description="`此操作不可恢复，确定要删除用户${deletingUser?.name}吗？`"
      :loading="loading"
      @confirm="confirmDeleteUser"
      @cancel="cancelDelete"
    />
  </div>
</template>
